<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 11/25/15
 * Time: 10:12 AM
 */

namespace Plugins\DataBase;

use PDO;

class Plugin_DataBase{
    private $db=null;

    public function __construct()
    {
        $this->initDB('127.0.0.1','root','root','jupiter');
    }

    public function initDB($host,$userName,$passWord,$dbName,$driver="mysql",$charset='utf-8'){
        $this->db = new PDO("$driver:host=$host;dbname=$dbName",$userName,$passWord);
        $this->exec("set names 'utf8'");
    }

    public function exec($sql){
        if($this->db===null){
            return;
        }
        $count = $this->db->exec($sql);
        return $count;
    }

    public function first($sql){
        $dataSet = $this->db->query($sql);
        if($dataSet!=null)
            return $dataSet->fetch(PDO::FETCH_OBJ);
    }

    public function get($sql){
        $dataSet = $this->db->query($sql);
        if($dataSet!=null)
            return $dataSet->fetchAll(PDO::FETCH_OBJ);
    }

    public function insert($table,$fill){
        if(is_array($fill)) {
            $sql = "insert into $table ";
            $field = "(";
            $value = "(";
            $count = 0;
            foreach ($fill as $key => $val) {
                $count++;
                if ($count == count($fill)) {
                    $field .= $key . ")";
                    $value .= "'$val')";
                } else {
                    $field .= $key . ",";
                    $value .= "'$val',";
                }
            }
            $sql .= $field . " values $value";
            return $this->exec($sql);
        }else{
            $sql = "insert into $table ".$fill;
            return $this->exec($sql);
        }
    }

    public function update($table,$fill,$where=""){
        if(is_array($fill)) {
            $sql = "update $table set ";
            $count = 0;
            foreach ($fill as $key => $val) {
                $count++;
                if ($count == count($fill)) {
                    $sql .= "$key='$val' ";
                } else {
                    $sql .= "$key='$val',";
                }
            }
            $sql .=$where;
            return $this->exec($sql);
        }
    }

    public function getError(){
        if($this->db->errorCode !='00000'){
            return $this->db->errorInfo();
        }
    }

}